package com.myrent.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.myrent.common.ReturnData;
import com.myrent.utils.JwtTokenUtil;
import com.myrent.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Map;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    RedisUtil redisUtil;

    /**命名：id的都用shopId，redis的是shop: ，实体类是enterprise
     * 企业的登录也要拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            Map<String, Claim> map = JwtTokenUtil.verifyToken(token);
            if (map != null) {
                String uuid = map.get("uuid").asString();
                String userId = map.get("userId").asString();
                String shopId = map.get("shopId").asString();
                if (uuid != null && userId != null && redisUtil.exist("user:" + userId)) {
                    request.setAttribute("userId", Integer.valueOf(userId));
                    String ret = (String) redisUtil.get("user:" + userId);
                    if (ret.equals(uuid)) {
                        redisUtil.expire("user:" + userId, 60 * 60 * 24 * 7);
                        return true;
                    }
                }
                else if (uuid != null && shopId != null && redisUtil.exist("shop:" + shopId)) {
                    request.setAttribute("shopId", Integer.valueOf(shopId));
                    String ret = (String) redisUtil.get("shop:" + shopId);
                    if (ret.equals(uuid)) {
                        redisUtil.expire("shop:" + shopId, 60 * 60 * 24 * 7);
                        return true;
                    }
                }
            }
        }
        //否则提示token过期,要求重新登录
        Writer writer = response.getWriter();
        writer.write(ReturnData.fail(-2, "token已过期,请重新登入").toString());
        writer.flush();
        return false;
    }


}
